<?

class db_migrate_task extends system_task
{
	public function execute( array $params = array() )
	{
		$this->out('Reading new migrations');
		$path = PROJECT_PATH . '/data/sql';
		
		$done_file = $path . '/done';
		$done = explode("\n", @file_get_contents($done_file));

		$files = glob("{$path}/*.sql");
		natsort($files);

		foreach ( $files as $file )
		{
			$fname = basename($file);
			if ( @in_array($fname, $done) ) continue;
			
			$data = file_get_contents($file);
			preg_match('/connection:(.+)/', $data, $m);
			$conf = config::get($m[1] ? $m[1] : 'mysql');

			$i++;

			if ( !in_array('mock', $params) )
			{
				$this->out('Executing ' . $fname . '...');
				exec("mysql -h {$conf['host']} -u {$conf['user']} -p{$conf['password']} {$conf['db']} < " . $file, $o, $r);
			}

			if ( !$r )
			{
				file_put_contents ($done_file, $fname . "\n", FILE_APPEND);
				$this->out('ok');
			}
			else
			{
				$this->error('something wrong with SQL - ' . $fname);
			}
		}

		$this->out( $i ? 'Migrated ' . $i . ' SQLs' : 'Nothing to migrate');
	}
}
